package com.systemsjr.mpf.db;

import java.util.HashMap;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import com.systemsjr.mpf.account.AccountInstance;

public class AccountInstanceContentProvider extends MpfContentProvider {
	public static final String AUTHORITY = "com.systemsjr.mpf.db.AccountInstanceContentProvider";
	private static final int ACCOUNT_INSTANCES = 1;
	private static final int INSTANCE_DESCRIPTION = 2;

	protected static UriMatcher sUriMatcher;
	protected static HashMap<String, String> projectionMap;

	@Override
	public boolean onCreate() {
		dbHelper = new MpfDbOpenHelper(this.getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(AccountInstance.TABLE_NAME);
		System.out.println(sUriMatcher.toString());
		System.out.println(uri.toString());
		switch (sUriMatcher.match(uri)) {
		case ACCOUNT_INSTANCES:
			qb.setProjectionMap(projectionMap);
			break;
		case INSTANCE_DESCRIPTION:
			String instance = uri.getPathSegments().get(
					AccountInstance.DESCRIPTION_PATH_POSITION);
			qb.setProjectionMap(projectionMap);
			qb.appendWhere(AccountInstance.INSTANCE + "=" + instance);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null,
				null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);

		return c;
	}

	@Override
	public String getType(Uri uri) {

		switch (sUriMatcher.match(uri)) {
		case ACCOUNT_INSTANCES:
			return AccountInstance.CONTENT_TYPE;
		case INSTANCE_DESCRIPTION:
			return AccountInstance.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {

		if (sUriMatcher.match(uri) != ACCOUNT_INSTANCES) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		ContentValues contentValues;

		if (values != null) {
			contentValues = new ContentValues(values);
		} else {
			contentValues = new ContentValues();
		}

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		long rowid = db.insert(AccountInstance.TABLE_NAME, null, contentValues);

		if (rowid > 0) {
			Uri accountInstanceUri = ContentUris.withAppendedId(
					AccountInstance.CONTENT_URI, rowid);
			getContext().getContentResolver().notifyChange(accountInstanceUri,
					null);
			return accountInstanceUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int count;

		switch (sUriMatcher.match(uri)) {
		case ACCOUNT_INSTANCES:
			count = db.delete(AccountInstance.TABLE_NAME, selection,
					selectionArgs);
			break;
		case INSTANCE_DESCRIPTION:
			String instance = uri.getPathSegments().get(
					AccountInstance.DESCRIPTION_PATH_POSITION);
			String finalWhere = AccountInstance.TABLE_NAME + " like %"
					+ instance + "%";
			if (selection != null) {
				finalWhere = finalWhere + selection;
			}

			count = db.delete(AccountInstance.TABLE_NAME, finalWhere,
					selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int count;

		switch (sUriMatcher.match(uri)) {
		case ACCOUNT_INSTANCES:
			count = db.update(AccountInstance.TABLE_NAME, values, selection,
					selectionArgs);
			break;
		case INSTANCE_DESCRIPTION:
			String instance = uri.getPathSegments().get(
					AccountInstance.DESCRIPTION_PATH_POSITION);
			String finalWhere = AccountInstance.TABLE_NAME + "=" + instance;
			if (selection != null) {
				finalWhere = finalWhere + selection;
			}

			count = db.update(AccountInstance.TABLE_NAME, values, finalWhere,
					selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, "accountInstance", ACCOUNT_INSTANCES);
		sUriMatcher
				.addURI(AUTHORITY, "accountInstance/#", INSTANCE_DESCRIPTION);
		// PROJECTION MAP USED FOR ROW ALIAS
		projectionMap = new HashMap<String, String>();
		projectionMap.put(AccountInstance.ID, AccountInstance.ID);
		projectionMap.put(AccountInstance.ACCOUNT_FK,
				AccountInstance.ACCOUNT_FK);
		projectionMap.put(AccountInstance.BUDGET, AccountInstance.BUDGET);
		projectionMap.put(AccountInstance.CLOSE_DATE,
				AccountInstance.CLOSE_DATE);
		projectionMap.put(AccountInstance.START_DATE,
				AccountInstance.START_DATE);
		projectionMap.put(AccountInstance.INSTANCE, AccountInstance.INSTANCE);
		projectionMap.put(AccountInstance.SPENT,
				"(SELECT sum(amount) FROM EXPENSE WHERE EXPENSE.ACCOUNT_INSTANCE_FK = ACCOUNT_INSTANCE."
						+ AccountInstance.ID + ") SPENT");
	}

}
